package org.example.springboot.controller;

import org.example.springboot.config.DeepSeekClient;
import org.example.springboot.entity.AIConversation;
import org.example.springboot.entity.AIMessage;
import org.example.springboot.service.ConversationStorage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/chat")
public class ChatController {
    private final DeepSeekClient deepSeekClient;
    private final ConversationStorage conversationStorage;
    private final Map<String, AIConversation> pendingConversations = new ConcurrentHashMap<>();

    public ChatController(@Value("${deepseek.api-key}") String apiKey,
                          ConversationStorage conversationStorage) {
        this.deepSeekClient = new DeepSeekClient(apiKey);
        this.conversationStorage = conversationStorage;
    }

    // 创建新会话
    @PostMapping("/new")
    public AIConversation createConversation(@RequestParam Long userId) {
        AIConversation conversation = deepSeekClient.createNewConversation();
        conversation.setUserId(userId);
        conversation.setTitle("新会话"); // 初始标题
        conversationStorage.saveConversation(conversation);
        return conversation;
    }

    // 发送消息
    @PostMapping("/send")
    public Map<String, String> sendMessage(@RequestParam Long userId,
                                           @RequestParam String conversationId,
                                           @RequestParam String message) {
        try {
            // 获取会话并验证用户权限
            AIConversation conversation = conversationStorage.getConversation(userId, conversationId);
            if (conversation == null) {
                return Collections.singletonMap("error", "会话不存在或无权访问");
            }

            // 如果是第一条用户消息，将其作为标题
            if (conversation.getAIMessages().size() == 1) { // 只有系统消息
                String title = message.length() > 20 ? message.substring(0, 20) + "..." : message;
                conversation.setTitle(title);
            }

            // 调用API并更新会话
            AIConversation updatedConversation = deepSeekClient.sendMessage(conversation, message);
            conversationStorage.saveConversation(updatedConversation);

            // 返回最新回复
            String reply = updatedConversation.getAIMessages().get(updatedConversation.getAIMessages().size() - 1).getContent();
            return Collections.singletonMap("content", reply);
        } catch (IOException e) {
            // 记录详细的错误日志
            System.out.println(e);

            // 根据错误类型返回不同的错误信息
            if (e.getCause() instanceof SocketTimeoutException) {
                return Collections.singletonMap("error", "请求超时，请稍后再试");
            } else {
                return Collections.singletonMap("error", "服务暂时不可用，请稍后再试");
            }
        }
    }

    // 流式发送消息 - 修改为接收POST请求
    @PostMapping(value = "/stream-send", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamSendMessage(@RequestBody Map<String, Object> requestBody) {
        Long userId = Long.valueOf(requestBody.get("userId").toString());
        String conversationId = (String) requestBody.get("conversationId");
        String message = (String) requestBody.get("message");

        SseEmitter emitter = new SseEmitter(120_000L); // 设置2分钟超时

        try {
            // 获取会话并验证用户权限
            AIConversation conversation = conversationStorage.getConversation(userId, conversationId);
            if (conversation == null) {
                emitter.completeWithError(new RuntimeException("会话不存在或无权访问"));
                return emitter;
            }

            // 如果是第一条用户消息，将其作为标题
            if (conversation.getAIMessages().size() == 1) { // 只有系统消息
                String title = message.length() > 20 ? message.substring(0, 20) + "..." : message;
                conversation.setTitle(title);
            }

            // 保存待完成的会话，以便完成后保存
            String sessionKey = userId + ":" + conversationId;
            pendingConversations.put(sessionKey, conversation);

            // 调用流式API
            deepSeekClient.streamSendMessage(conversation, message, emitter);

            // 设置完成和超时回调
            emitter.onCompletion(() -> {
                // 保存完成的会话
                AIConversation completedConversation = pendingConversations.remove(sessionKey);
                if (completedConversation != null) {
                    conversationStorage.saveConversation(completedConversation);
                }
            });

            emitter.onTimeout(() -> {
                AIConversation timedOutConversation = pendingConversations.remove(sessionKey);
                emitter.completeWithError(new IOException("请求超时"));
            });

        } catch (Exception e) {
            emitter.completeWithError(e);
        }

        return emitter;
    }
    // 获取会话历史
    @GetMapping("/history/{userId}/{conversationId}")
    public AIConversation getHistory(@PathVariable Long userId,
                                     @PathVariable String conversationId) {
        AIConversation conversation = conversationStorage.getConversation(userId, conversationId);
        if (conversation == null) {
            throw new RuntimeException("会话不存在或无权访问");
        }
        return conversation;
    }

    // 获取用户的所有会话列表
    @GetMapping("/list/{userId}")
    public List<AIConversation> getConversationList(@PathVariable Long userId) {
        return conversationStorage.getUserConversations(userId);
    }

    // 删除会话
    @DeleteMapping("/delete/{userId}/{conversationId}")
    public boolean deleteConversation(@PathVariable Long userId,
                                      @PathVariable String conversationId) {
        return conversationStorage.deleteConversation(userId, conversationId);
    }

    // 更新会话标题
    @PostMapping("/title/{userId}/{conversationId}")
    public boolean updateTitle(@PathVariable Long userId,
                               @PathVariable String conversationId,
                               @RequestParam String title) {
        AIConversation conversation = conversationStorage.getConversation(userId, conversationId);
        if (conversation == null) {
            return false;
        }

        conversation.setTitle(title);
        conversationStorage.saveConversation(conversation);
        return true;
    }
}